package codegenjvm;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;

import ast.Class_;

import util.ClassTreeNode;

/*	
	Alexander Sedgwick
	Rebeen Hawramy
*/

public class JVMCodeGenerator
{
	//ArrayList<String> classNames;
	FileOutputStream fstream; 
	DataOutputStream out;
	BufferedWriter bw;
	Class_ classNode;
	CodeGenVisitor cgv;
	
	String className;
	ClassTreeNode classTree;
	boolean debugCodeGen;
	
	public JVMCodeGenerator(ClassTreeNode classTree, boolean debugCodeGen)
	{
		this.classTree = classTree;
		CodeGenVisitor.setClassRoot(classTree);
		this.debugCodeGen = debugCodeGen;
	}
	public void generate()
	{
		generateHelper(classTree);
	}
	public void generateHelper(ClassTreeNode node)
	{
		
		if(!node.isBuiltIn()) {
			cgv = new CodeGenVisitor(node);
			ArrayList<String> lineList = (ArrayList<String>) node.getASTNode().accept(cgv);
			try {
				classNode = (Class_) node.getASTNode();
				fstream = new FileOutputStream(classNode.getName() + ".j");
				out = new DataOutputStream(fstream);
				bw = new BufferedWriter(new OutputStreamWriter(out));
				
				for(int i = 0; i < lineList.size(); i++) {
					bw.write(lineList.get(i) + "\n");
					System.out.println((i+1) + ":" + lineList.get(i));
				}
				bw.close();
				out.close();
				fstream.close();
		 	}catch (Exception e){//Catch exception if any
		    	System.err.println("Read Error: " + e.getMessage());
		    	System.err.println(e.getStackTrace());
		    	System.err.println(e.getLocalizedMessage());
		    }
		}
	 	Iterator<ClassTreeNode> classes = node.getChildrenList();
	 	while(classes.hasNext()) {
	 		generateHelper(classes.next());
	 	}
	}
}
